package site.icesky.springboot.feign.config;

import feign.Client;
import feign.Request;
import feign.Retryer;
import okhttp3.ConnectionPool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import site.icesky.springboot.feign.controller.FeignController;

import java.util.concurrent.TimeUnit;

/**
 * @ClassName: FeignConfig <br>
 * @Description: feign的配置启动类 <br>
 * @Package: site.icesky.springboot.feign.config <br>
 * @author: suitianmou <br>
 * @Date: 2020/6/5-16:34 <br>
 * @version: 1.0 <br>
 * @see <br>
 * @since (从产品的哪一个版本此类被添加进来 ( 可选))<br>
 * 修改历史: <br>
 * 修改时间             修改人           版本变更           修改说明<br>
 * -----------------------------------------------------<br>
 * <br>
 */
@Configuration
public class FeignConfig {

    private static final Logger logger = LoggerFactory.getLogger(FeignController.class);

    // HTTP连接超时时间
    @Value("${feign.comm.conntime}")
    private int connTimeout;

    // HTTP接收超时时间
    @Value("${feign.comm.recvtime}")
    private int recvTimeout;

    // 最大空闲连接
    @Value("${feign.comm.maxidleconnections}")
    private int maxIdleConnections;

    // 活跃连接数
    @Value("${feign.comm.keepaliveduration}")
    private long keepAliveDuration;


    /** 获取重试对象
     *
     * @return
     */
    @Bean
    public Retryer feignRetryer(){
        //参数1： 发起当前请求的时间间隔
        //参数2： 发起请求的最大时间
        //参数3： 最大请求次数
        logger.info("设置feignRetryer的默认参数为-100");
        return new Retryer.Default(100, TimeUnit.SECONDS.toMillis(1), 0);
    }

    /** 创建HTTP参数选项
     *
     * @return
     */
    @Bean
    public Request.Options createOptions(){
        // 连接时间
        // 读取时间，超过读取时间后发送下一次请求
        logger.info("设置createOptions的参数：连接时间-[{}]，读取时间-[{}]", connTimeout, recvTimeout);
        return new Request.Options( connTimeout, recvTimeout);
    }

    /** 获取HTTP客户端对象
     *
     * @return
     */
    @Bean
    public Client feignClient(){
        logger.info("创建feignClient，参数：连接时间-[{}], 读取时间-[{}], 写入时间-10000, 连接池数量-[{}][{}]",
                connTimeout, recvTimeout, maxIdleConnections, keepAliveDuration);
        okhttp3.OkHttpClient okHttpClient = new okhttp3.OkHttpClient.Builder()
                .connectTimeout(connTimeout, TimeUnit.MILLISECONDS)
                .readTimeout(recvTimeout, TimeUnit.MILLISECONDS)
                .writeTimeout(10000, TimeUnit.MILLISECONDS)
                // 默认5个活跃连接
                .connectionPool(new ConnectionPool( maxIdleConnections, keepAliveDuration, TimeUnit.MINUTES))
                .build();
        return new feign.okhttp.OkHttpClient(okHttpClient);
    }
}
